<template>
  <div class="container">
    <h1>{{ id ? "编辑账单" : "新建账单" }}</h1>
    <hr style="border: 1px solid rgb(240, 240, 240)" />
    <span>基础信息</span>
    <div class="body">
      <div class="input">
        <div class="input-left">
          <span>账单名称</span>
        </div>
        <div class="input-right">
          <el-input v-model="bill_name" placeholder="请输入" />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>收费项目</span>
        </div>
        <div class="input-right">
          <el-select v-model="charge_item" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>走字</span>
        </div>
        <div class="input-right">
          <el-input v-model="usage" placeholder="请输入" />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>费用单价</span>
        </div>
        <div class="input-right">
          <el-input v-model="price" type="number" disabled />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>计算公式</span>
        </div>
        <div class="input-right">
          <el-input v-model="formula" disabled />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>计量单位</span>
        </div>
        <div class="input-right">
          <el-input v-model="unit" disabled />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>计算精度</span>
        </div>
        <div class="input-right">
          <el-input v-model="precision" disabled />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>滞纳金比例</span>
        </div>
        <div class="input-right">
          <el-input v-model="scale" disabled />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>收费范围</span>
        </div>
        <div class="input-right">
          <el-input v-model="range" />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>起止日期</span>
        </div>
        <div class="input-right">
          <el-date-picker
            v-model="date"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </div>
      </div>
      <div class="input">
        <div class="input-left">
          <span>备注</span>
        </div>
        <div class="input-right">
          <el-input v-model="remark" type="textarea" :rows="5" />
        </div>
      </div>
      <div style="margin: 2rem 0 2rem 12rem">
        <el-button
          type="primary"
          style="margin-left: 9rem"
          @click="addOrUpdate"
        >
          提交
        </el-button>
        <el-button @click="to('payment/bill')">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import to from "@/utils/to.js";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";

const route = useRoute();
const id = route.query.id;

const bill_name = ref("");
const charge_item = ref("");
const usage = ref(0);
const price = ref(0);
const formula = ref("");
const unit = ref("");
const precision = ref("");
const scale = ref(0);
const range = ref("");
const date = ref([]);
const remark = ref("");

const options = ref([]);

watch(charge_item, (newValue) => {
  const config = {
    url: "http://localhost:8080/pay/item/getByName",
    method: "GET",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
    params: {
      name: newValue,
    },
  };

  const response = axios(config);
  response
    .then((data) => {
      price.value = data.data.data.unitPrice;
      formula.value = data.data.data.formula;
      unit.value = data.data.data.unit;
      precision.value = data.data.data.calculationPrecision;
      scale.value = data.data.data.lateFeeRate;
    })
    .catch((error) => {
      console.log(error);
    });
});

const fetchBillData = async () => {
  try {
    const response = await axios.get(
      `http://localhost:8080/pay/bill/get/${id}`,
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
      }
    );
    if (response.data.code === 1) {
      const billData = response.data.data;
      bill_name.value = billData.billName;
      charge_item.value = billData.item;
      usage.value = billData.usage;
      price.value = billData.unitPrice;
      formula.value = billData.formula;
      unit.value = billData.unit;
      precision.value = billData.calculationPrecision;
      scale.value = billData.lateFeeRate;
      range.value = billData.scope;
      date.value = [new Date(billData.startDate), new Date(billData.endDate)];
      remark.value = billData.remark;
    } else {
      ElMessage.error("获取账单数据失败");
    }
  } catch (error) {
    console.error(error);
  }
};

const getPayItem = () => {
  const config = {
    url: "http://localhost:8080/pay/item/getAll",
    method: "GET",
    headers: {
      Authorization: localStorage.getItem("token"),
    },
  };

  const response = axios(config);
  response
    .then((data) => {
      options.value = data.data.data.map((item) => ({
        value: item.itemName,
        label: item.itemName,
      }));
    })
    .catch((error) => {
      console.log(error);
    });
};

const addOrUpdate = async () => {
  try {
    const config = {
      url: id
        ? "http://localhost:8080/pay/bill/updateBill"
        : "http://localhost:8080/pay/bill/createBill",
      method: id ? "PUT" : "POST",
      headers: {
        Authorization: localStorage.getItem("token"),
      },
      data: {
        id: id ? id : null,
        billName: bill_name.value,
        item: charge_item.value,
        usage: usage.value,
        unitPrice: price.value,
        formula: formula.value,
        unit: unit.value,
        calculationPrecision: precision.value,
        lateFeeRate: scale.value,
        scope: range.value,
        startDate: date.value[0].getTime(),
        endDate: date.value[1].getTime(),
        remark: remark.value,
      },
    };

    const response = await axios(config);
    if (response.data.code === 1) {
      ElMessage.success(response.data.msg);
      setTimeout(() => {
        to("payment/bill");
      }, 2000);
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    console.error("提交表单时出错:", error);
    ElMessage.error("提交表单时出错");
  }
};

onMounted(() => {
  if (id) {
    fetchBillData();
  }
  getPayItem();
});
</script>

<style scoped>
.container {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin: 1rem 2rem 1rem 0;
  line-height: 24px;
  width: 100px;
  text-align: right;
}

.body {
  display: grid;
  justify-content: center;
  align-items: center;
}

.input {
  display: flex;
  justify-content: center;
  align-items: center;
  width: auto;
}

.input-right {
  width: 370px;
}
</style>
